import React, { Component } from 'react';
// import { RefMultipleTableWithInput, SearchPanelItem } from 'ref-multiple-table';
import { RefMultipleTableWithInput } from 'ref-multiple-table'
import {RefTreeWithInput} from'ref-tree';
import 'ref-tree/lib/index.css'
import 'ref-multiple-table/lib/index.css';
import { Button, Form, FormControl } from 'tinper-bee';
import request from 'utils/request';
import {StringData} from "utils";

let options = {}
export class RefTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showLoading: false,
      showModal: false,
      matchData: [
        {
          "code":"005",
          "mobile": "15011430235",
          "name": "人员5",
          "refpk": "5e3a85ec-5e14-4734-8b3a-1e6168426c89",
          "refname": "人员5",
          "email": "55@26.com"
        }
      ],
      value: '{"refname":"人员5-自定义","refpk":"5e3a85ec-5e14-4734-8b3a-1e6168426c89"}',
    };
    this.page = {
      pageCount: 0,
      pageSize: 10,
      currPageIndex: 1,
    };
    this.tableData = [];
    this.columnsData = [];
    this.fliterFormInputs = [];

  }
  componentDidMount() {
    this.loadData();
  }
  /**
   * @msg: 请求mock数据，包含表头数据和表体数据
   * @param {type} 
   * @return: 
   */
  loadData = async () => {
    let {param} = this.props;

    let refModelUrl = {
      tableBodyUrl: '/uitemplate_web/iref_ctr/commonRefsearch',//表体请求
      refInfo: '/uitemplate_web/iref_ctr/matchPKRefJSON/',//表头请求
    }

    let url = '/uitemplate_web/iref_ctr/commonRefsearch';

    let ajax={
        data:StringData(param),
        method: 'post',
        ContentType:"application/x-www-form-urlencoded;charset=utf-8" 
    };

    let requestList = [
      //request(refModelUrl.refInfo, refdata),//表头数据 data = StringData(data);
      request(url,ajax), //表体数据
    ];
    Promise.all(requestList).then(([columnsData, bodyData]) => {
      this.launchTableHeader(columnsData);
      this.launchTableData(bodyData);
      this.setState({
        showLoading: false
      });
    }).catch((e) => {
      this.launchTableHeader({});
      this.launchTableData({});
      this.setState({
        showLoading: false
      });
      console.log(e)
    });;
  }
  /**
 * 根据 refinfo 返回结果拆解并渲染表格表头
 * @param {object} data 
   * 注意：单选时候自己添加radio
 */
  launchTableHeader = (data) => {
    if (!data) return;
    let keyList = data.strFieldCode || [];
    let titleList = data.strFieldName || [];
    let colunmsList = keyList.map((item, index) => {
      this.fliterFormInputs.push(
        <SearchPanelItem key={item} name={item} text={titleList[index]}>
          <FormControl size={'sm'} />
        </SearchPanelItem>
      )
      return {
        key: item,
        dataIndex: item,
        title: titleList[index]
      }
    });
    if (colunmsList.length === 0) {
      colunmsList = [{ title: "未传递表头数据", dataIndex: "nodata", key: "nodata" }];
    }
    this.columnsData = colunmsList;
  }
	/**
	 * 处理并渲染表格数据
	 */
  launchTableData = (response) => {
    if (!response) return;
    let { valueField } = options;
    let { data = [], page = {} } = response;
    data.map((record, k) => {
      record.key = record[valueField];
      return record;
    });
    this.tableData = data;
    this.page = {
      pageCount: page.pageCount || 0,
      currPageIndex: page.currPageIndex + 1 || 0,
      totalElements: page.totalElements || 0
    }
  }
  /**
   * @msg: 简单搜索的回调，与复杂搜索的回调不是同一个
   * @param {type} 
   * @return: 
   */
  searchFilterInfo = (value) => {
    alert('搜索' + JSON.stringify(value))
  }

  /**
   * 跳转到制定页数的操作
   * @param {number} index 跳转页数
   */
  handlePagination = (index) => {
    this.page.currPageIndex = index;
    this.setState({ number: Math.random() })
  }
	/**
	 * 选择每页数据个数
	 */
  dataNumSelect = (index, pageSize) => {
    console.log(index, pageSize)
  }
  /**
   * @msg: modal框确认按钮
   * @param {type} 
   * @return: 
   */
  onSave = (item) => {
    this.checkedArray = item;
    this.setState({
      showModal: false,
      matchData: item,
    })
  }
  /**
   * @msg: modal框右上X和右下角取消
   * @param {type} 
   * @return: 
   */
  onCancel = () => {
    this.setState({ showModal: false })
  }

  render() {
    let { showLoading, showModal, matchData, value } = this.state;
    let { columnsData, tableData, page, fliterFormInputs } = this;
    options = {
      miniSearch: false,
      multiple: true,
      valueField: "refpk",
      displayField: "{code}-    {name}",
      emptyBut: true
    }
    let childrenProps = Object.assign({}, options, {
      showModal: showModal,
      showLoading: showLoading,
      columnsData: columnsData,
      tableData: tableData,
      fliterFormInputs: fliterFormInputs,
      ...page,
      matchData,
      searchFilterInfo: this.searchFilterInfo,
      dataNumSelect: this.dataNumSelect,
      handlePagination: this.handlePagination,
      onSave: this.onSave,
      onCancel: this.onCancel,
    });
    return (
        <RefMultipleTableWithInput
          {...childrenProps}
          filterUrl={'https://mock.yonyoucloud.com/mock/1264/pap_basedoc/common-ref/blobRefTreeGrid'}
          {...this.props}
        />
    )
  }
}


export class RefTree extends Component {
  constructor() {
      super();
      this.state = {
          value:'{"refname":"用友集团","refpk":"001"}',
          treeData:[],
          matchData:[{name:'用友集团',refname:'用友集团',code:'001'}],
      }
  }
  componentDidMount(){
    this.loadData();
  }
  /**
   * @msg: 打开input右侧menu icon触发的操作
   * @param {type} 
   * @return: 
   */
  canClickGoOn = () =>{
      this.loadData();
      return true;//必须要有
  }
  /**
   * @msg: 请求mock数据
   */
  loadData = async () => {
      let {param} = this.props;
      this.setState({
        loading:true,
      })
      let url = '/uitemplate_web/iref_ctr/commonRefsearch';
      let temp = "pk_val=&filterPks=&refModelUrl=%2Focc-base%2Fbase%2Fcustomer-category-ref%2F&pk_org=&transmitParam=&refName=%2525E5%2525AE%2525A2%2525E6%252588%2525B7%2525E5%252588%252586%2525E7%2525B1%2525BB&refCode=&refModelClassName=&refModelHandlerClass=&cfgParam=%7B%22ctx%22%3A%22%2Fuitemplate_web%22%2C%22refName%22%3A%22%E5%AE%A2%E6%88%B7%E5%88%86%E7%B1%BB%22%7D&clientParam=%7B%22AUTH_refcod%22%3A%22customer%22%2C%22AUTH_refdim%22%3A%22customerCategory%22%7D&refClientPageInfo.pageSize=-1&refClientPageInfo.currPageIndex=0";
      let ajax={
          //data:StringData(param),
          data:temp,
          method: 'post',
          ContentType:"application/x-www-form-urlencoded;charset=utf-8" 
      };

      let results = await request(url,ajax);
      let treeData = [];
      if (!results || !results.data.length){
        this.setState({ 
          loading:false,
          pageCount:-1,//不展示分页
          totalElements:0,
          treeData,
        });
        return false;
      }
      treeData = results.data;
      let page = results.page;
      this.setState({ 
        treeData,
         ...page,
         loading:false 
      });
      
  }
  
  /**
   * @msg: 保存操作的回调
   * @param {type} 
   * @return: 
   */
  onSave = (result) =>{
      console.log(result)
      this.setState({
          matchData:result,
      })
  }
  /**
   * @msg: 清空操作
   * @param {type} 此时value不可以直接传'',因为''下只能清除一次，第二次清除时前后value都是''，不会触发更新操作，
   * 因此通过refpk不一致来触发更新操作
   * @return: 
   */
  clearFunc = () =>{
      this.setState({
          matchData:[],
          value:`{"refname":"","refpk":"${Math.random()}"}`,
      })
  }
  render() {
      const {treeData,matchData,value} = this.state;
      return (
          <div className="demoPadding">
              <RefTreeWithInput
                  emptyBut={true}
                  nodeDisplay={ (record) => {
                      return record.refname
                  }}
                  displayField={ (record) => {
                      return record.code
                  }}  //显示内容的键
                  valueField={ 'code'}    //真实 value 的键
                  multiple={true}
                  onSave={this.onSave}
                  matchData={matchData}
                  treeData={treeData}
                  canClickGoOn={this.canClickGoOn}
                  value={value}
              >
              </RefTreeWithInput>
              <Button  
                  colors="primary"
                  onClick={this.clearFunc}>清空</Button>
             
          </div>
      )
  }
};